package com.fc.v2.controller.api;


import cn.hutool.core.util.RandomUtil;
import com.fc.v2.common.conf.redis.RedisService;
import com.fc.v2.common.domain.AjaxResult;
import com.fc.v2.util.AliSmsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Api(value = "短信验证")
@Controller
@RequestMapping("/api/sms")
public class ASmsController {
    @Autowired
    private RedisService redisService;

    /**
     * 发送短信
     *
     * @param id
     * @param mmap
     * @return
     */
    @ApiOperation(value = "发送短信", notes = "发送短信")
    @GetMapping("/send")
    @ResponseBody
    public AjaxResult send(String phone) {
       //发送短信
        String code = RandomUtil.randomNumbers(6);
        try {
            AliSmsUtils.sendVerifyIdentity(phone,code);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("发送验证码失败");
        }

        String key = "sms:" + phone;
        redisService.setCacheObject(key,code);
        if(!redisService.expire(key,300)){
            return AjaxResult.error("发送验证码错误，请重试");
        }
        return AjaxResult.success("发送成功");
    }

    /**
     * 验证短信
     * @param phone
     * @return
     */
    @ApiOperation(value = "验证短信", notes = "验证短信")
    @GetMapping("/verify")
    @ResponseBody
    public AjaxResult verify(String phone,String code) {
        //验证短信
        String key = "sms:" + phone;
        String value = (String) redisService.getCacheObject(key);
        if(value==null){
            return AjaxResult.error(502,"验证码已失效");
        }

        if(code.equals(value)){
            redisService.deleteObject(key);
            return AjaxResult.success("验证码正确");
        }else{
            return AjaxResult.error(501,"验证码错误");
        }
    }
}
